package com.lapian.theparallelflow;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Vector;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.stream.LongStream;

/**
 * 创建日期：2021/11/9 14:41
 *
 * @author tony.sun
 * 类说明：
 */

public class TestForkJoin {
    @Test
    public void test1(){
        //获取运行前时间
        Instant start = Instant.now();
        //并行流池
        ForkJoinPool pool = new ForkJoinPool();
        ForkJoinTask<Long> task=new ForkJoinCalculate(0,10000000000L);
        Long sum = pool.invoke(task);
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println("耗费时间为："+ Duration.between(start,end).toMillis());//1亿是39，100亿是808
    }
    /**
     * 普通for
     */
    @Test
    public void test2(){
        Instant start = Instant.now();
        long sum=0L;
        for (long i = 0; i < 10000000000L; i++) {
            sum+=i;
        }
        System.out.println(sum);
        Instant end = Instant.now();
        System.out.println("耗费时间为："+ Duration.between(start,end).toMillis());//1亿是27,100亿是2400
    }
    /**
     * java8
     */
    @Test
    public void test3(){
        Instant start = Instant.now();

        LongStream.rangeClosed(0,10000000000L)
                .parallel()
                .reduce(0,Long::sum);

        Instant end = Instant.now();
        System.out.println("耗费时间为："+ Duration.between(start,end).toMillis());//100亿是651


    }


}
